package com.dayuanit.dy15.atm.controller;

import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@PropertySource("classpath:atm.properties")
public abstract class BaseController {

    protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Value("${websocket.voice.url}")
    protected String websocketVoiceUrl;

    @Value("${websocket.ws.url}")
    protected String websocketUrl;


    protected long getUserId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (null == user) {
            throw new BizException("请先登录");
        }
        return user.getId();

//        return 1004L;
    }


    protected void savaUserStatus(User user, HttpSession session) {
        session.setAttribute("loginUser", user);
        session.setAttribute("websocketVoiceUrl", websocketVoiceUrl);
        session.setAttribute("websocketUrl", websocketUrl);
    }

    /**
     * spring的统一异常处理
     * @param be
     * @return
     */
    @ExceptionHandler(BizException.class)
    public ResponseDTO processBizException(BizException be) {
        logger.error(be.getMessage(), be);
        return ResponseDTO.fail(be.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseDTO processException(Exception e) {
        logger.error(e.getMessage(), e);
        return ResponseDTO.fail("请联系客服");
    }
}
